# @time     :2022/1/16
# @Author   :Simple
# @FileName :base_page

from appium.webdriver import WebElement
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException


class BasePage:
    def __init__(self, driver: WebDriver):
        self.driver = driver
        self.driver.implicitly_wait(5)

    def swipe_find(self, text, num=3) -> WebElement:
        """
        滑动查找元素
        :param text: 元素text内容
        :param num: 滑动次数
        :return:
        """
        for i in range(num):
            if i == num - 1:
                self.driver.implicitly_wait(5)
                raise NoSuchElementException(f"找了{num}次，未找到。")
            self.driver.implicitly_wait(1)
            try:
                element = self.driver.find_element(MobileBy.XPATH, f"//*[@text='{text}']")
                self.driver.implicitly_wait(5)
                return element
            except:
                print("未找到")
                size = self.driver.get_window_size()
                width = size.get('width')
                height = size.get('height')
                start_x = width / 2
                start_y = height * 0.8
                end_x = start_x
                end_y = height * 0.2
                self.driver.swipe(start_x, start_y, end_x, end_y, 1000)

    def scroll_find(self, text):
        """
        滚动查找元素
        :param text: 元素text内容
        :return:
        """
        value = f'new UiScrollable(new UiSelector().scrollable(true).instance(0))' \
                f'.scrollIntoView(new UiSelector().text("{text}").instance(0));'
        return self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR, value)
